﻿using System.Data.SqlClient;
using System.IO;
class A
{
    public static void WriteVideo(string inputFileName)
    {
        try
        {
            using (SqlConnection dbCon = new SqlConnection("ASD"))
            {
                using (SqlCommand cmdCreateVideo = dbCon.CreateCommand())
                {
                    dbCon.Open();

                    using (FileStream fileReader = new FileStream(inputFileName, FileMode.Open, FileAccess.Read))
                    {
                        byte[] buffer = new byte[1024 * 1024];

                        int bytesRead = fileReader.Read(buffer, 0, buffer.Length);
                        cmdCreateVideo.CommandText = @"INSERT INTO Videos(VideoData) " +
                                    "VALUES (@setOfBits) ";
                        cmdCreateVideo.Parameters.AddWithValue("@setOfBits", buffer);
                        cmdCreateVideo.ExecuteNonQuery();

                        SqlCommand cmdSelectIdentity = new SqlCommand("SELECT @@Identity", dbCon);
                        int insertedVideoID = (int)(decimal)cmdSelectIdentity.ExecuteScalar();

                        while (true)
                        {
                            bytesRead = fileReader.Read(buffer, 0, buffer.Length);
                            if (bytesRead == 0)
                            {
                                break;
                            }
                            if (bytesRead < 1024 * 1024)
                            { 
                                byte[] newBuff = new byte[bytesRead];
                                cmdCreateVideo.Parameters.Clear();
                                cmdCreateVideo.Parameters.AddWithValue("@setOfBits", newBuff);
                            }
                            cmdCreateVideo.CommandText = @"UPDATE Videos " +
                                "SET VideoData = VideoData + @setOfBits " +
                                "WHERE VideoID = @insertedVideoID ";
                            if (!cmdCreateVideo.Parameters.Contains("@insertedVideoID"))
                            {
                                cmdCreateVideo.Parameters.AddWithValue("@insertedVideoID", insertedVideoID);
                            }
                            cmdCreateVideo.ExecuteNonQuery();
                        }

                    }
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            return;
        }
    }
}